package com.mzj.saas.jobs.lifePay.service;

import com.mzj.saas.jobs.commons.DateUtils;
import com.mzj.saas.jobs.lifePay.entity.EstatePaymentOrder;
import com.mzj.saas.jobs.lifePay.entity.HousePaymentOrder;
import com.mzj.saas.jobs.lifePay.repository.EstatePaymentOrderRepository;
import com.mzj.saas.jobs.lifePay.repository.HousePaymentOrderRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 生活缴费-缴费记录统计
 */
@Service
public class LifePayService {

    private static Logger log = LoggerFactory.getLogger(LifePayService.class);

    private static Map<String, Object> dateMap = new HashMap<>();

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private HousePaymentOrderRepository housePaymentOrderRepository;
    @Autowired
    private EstatePaymentOrderRepository estatePaymentOrderRepository;

    public String work() throws Exception {

        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMM");
        String lDate = formatter.format(date);

        List<String> datas = new ArrayList<>();
        SimpleDateFormat df = new SimpleDateFormat("HH");
        String str = df.format(date);
        int hh = Integer.parseInt(str);
        if (hh >= 0 && hh <= 6) {
            //判断到凌晨只统计一次昨天数据
            Date day = DateUtils.getYesterday(new Date());
            String yesterday = formatter.format(day);
            if (!dateMap.containsKey(yesterday)) {
                dateMap.clear();
                dateMap.put(yesterday, yesterday);
                datas.add(yesterday);
            }
        }
        datas.add(lDate);

        //所有支付用户id
        List<String> userIds = new ArrayList<>();
        List<String> houseUserIds = housePaymentOrderRepository.findAll().stream().map(HousePaymentOrder::getPayUserId).distinct().collect(Collectors.toList());
        List<String> estateUserIds = estatePaymentOrderRepository.findAll().stream().map(EstatePaymentOrder::getPayUserId).distinct().collect(Collectors.toList());
        userIds.addAll(houseUserIds);
        userIds.addAll(estateUserIds);
        userIds = userIds.stream().distinct().collect(Collectors.toList());

        for (String localDate : datas) {
            log.info("LifePayService 生活缴费-缴费记录统计 start date={}", localDate);

            //删除当前统计时间记录
            String deleteMxSQL = "delete from saas_living_payment_total where stat_date = " + localDate;
            jdbcTemplate.execute(deleteMxSQL);

            for (String userId : userIds) {
                //查询用户当天支付记录
                String sql = "SELECT t.business_type AS businessType,SUM(t.bill_amount) as totalAmount FROM\n" +
                        "(SELECT r.business_type,r.bill_amount,o.pay_user_id,o.pay_result,o.pay_time\n" +
                        "FROM saas_house_payment_order_relation r JOIN saas_house_payment_order o\n" +
                        "ON r.order_number = o.order_number \n" +
                        "UNION ALL\n" +
                        "SELECT r.business_type,r.bill_amount,o.pay_user_id,o.pay_result,o.pay_time\n" +
                        "FROM saas_estate_payment_order_relation r JOIN saas_estate_payment_order o\n" +
                        "ON r.order_number = o.order_number) t\n" +
                        "WHERE t.pay_user_id = ? AND DATE_FORMAT(t.pay_time,'%Y%m') = ? AND t.pay_result = 1\n" +
                        "GROUP BY t.business_type";
                List<Object> args = new ArrayList<>();
                args.add(userId);
                args.add(localDate);
                List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, args.toArray());

                for (Map<String, Object> map : list) {
                    Integer businessType = Integer.parseInt(map.get("businessType").toString());
                    Integer totalAmount = Integer.parseInt(map.get("totalAmount").toString());
                    //费用类型转换
                    Integer type = null;
                    if (businessType == 1) {
                        type = 8;
                    } else if (businessType == 2) {
                        type = 1;
                    } else if (businessType == 3) {
                        type = 2;
                    } else if (businessType == 4) {
                        type = 3;
                    } else if (businessType == 5) {
                        type = 4;
                    } else if (businessType == 6) {
                        type = 5;
                    } else if (businessType == 7) {
                        type = 6;
                    } else if (businessType == 8) {
                        type = 7;
                    } else if (businessType == 9) {
                        type = 9;
                    }else if (businessType == 10) {
                        type = 10;
                    }

                    //数据插入
                    String insertSql = "INSERT INTO saas_living_payment_total (user_id,stat_date,type,total_amount) VALUE (?,?,?,?)";
                    Integer finalType = type;
                    log.info("insert, userId={}, localDate={}, finalType={}, totalAmount={}", userId, localDate, finalType, totalAmount);
                    jdbcTemplate.update(insertSql, ps -> {
                        ps.setString(1, userId);
                        ps.setString(2, localDate);
                        ps.setInt(3, finalType);
                        ps.setInt(4, totalAmount);
                    });
                }
            }

            log.info("LifePayService 生活缴费-缴费记录统计 end");
        }

        return "SUCCESS";
    }

}
